package ign.behaviours.ihm;

import ign.Performatives;
import ign.agents.IHM;
import jade.core.AID;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import java.awt.Rectangle;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Comportement vérifiant l'existence de conflits entres 
 * tous les agents actuellement sur la carte.
 * @author Simon Bourigaut & Ghislain Di Paolo
 */
public class CheckConflicts extends Behaviour {
	private static final long serialVersionUID = -744003483727204464L;
	
	public CheckConflicts() {
		
	}

	@Override
	public void action() {
		
		this.block();
		IHM ihm = (IHM) myAgent;
		
		Map<AID, Rectangle> all = ihm.getAllPositions();
		
		for (Entry<AID, Rectangle> first : all.entrySet()) {
			AID aid = first.getKey();
			Rectangle rect = first.getValue();
			
			for (Entry<AID, Rectangle> e : all.entrySet()) {
				AID curaid = e.getKey();
				Rectangle currect = e.getValue();
				
				/* Evite les comparaisons doubles */
				if (aid.compareTo(curaid) <= 0)
					continue ;
				
				/* Check collision */
				if(currect.intersects(rect)) {
					
					/* Envoie les messsages */
					ACLMessage mess1 = new ACLMessage(Performatives.IN_CONFLICT);
					ACLMessage mess2 = new ACLMessage(Performatives.IN_CONFLICT);
					mess1.setContent(aid.getName());
					mess2.setContent(curaid.getName()) ;
					mess1.addReceiver(curaid);
					mess2.addReceiver(aid);
					
					myAgent.send(mess2);
					myAgent.send(mess1);
				}
			}			
		}
	}

	@Override
	public boolean done() {
		
		return false;
	}
}
